package com.applet.web.controller.system;

import com.applet.common.annotation.Log;
import com.applet.common.core.controller.BaseController;
import com.applet.common.core.domain.AjaxResult;
import com.applet.common.core.domain.entity.SysUser;
import com.applet.common.core.domain.model.LoginUser;
import com.applet.common.core.redis.RedisCache;
import com.applet.common.enums.BusinessType;
import com.applet.common.utils.SecurityUtils;
import com.applet.common.utils.StringUtils;
import com.applet.common.utils.file.AliyunOssUploadUtils;
import com.applet.framework.web.service.TokenService;
import com.applet.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AliyunOssUploadUtils aliOssUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        if (Objects.equals(user.getSex(), "男")) {
            currentUser.setSex("0");
        } else if (Objects.equals(user.getSex(), "女")) {
            currentUser.setSex("1");
        } else {
            currentUser.setSex("2");
        }
        if (!Pattern.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", user.getEmail())) {
            return error("邮箱格式不正确");
        }
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
//        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
            return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }


    /**
     * 找回密码
     */
    @PutMapping("/recoverPassword")
    public AjaxResult recoverPassword(String userName, String newPassword, String code) {
        //取出存在缓存的验证码与用户输入的进行对比
        if (!Objects.equals(redisCache.<String>getCacheObject(userName), code)) {
            return error("验证码错误");
        }
        //对新密码进行加密,在存入数据库
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            return success();
        }
        return error("找回密码失败，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) {
//        if (!file.isEmpty())
//        {
//            LoginUser loginUser = getLoginUser();
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
//            {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", avatar);
//                // 更新缓存用户头像
//                loginUser.getUser().setAvatar(avatar);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
//        }
//        return error("上传图片异常，请联系管理员");
        if (!file.isEmpty()) {
            LoginUser loginUser = getLoginUser();
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            try {
                //获取原始文件名
                String originName = file.getOriginalFilename();
                //截取原始文件名后缀 abc.png
                String suffix = null;
                if (originName != null) {
                    suffix = originName.substring(originName.lastIndexOf("."));
                }
                //构造新文件名称
                String newName = UUID.randomUUID() + suffix;
                String url = aliOssUtil.upload(file.getBytes(), newName);
                AjaxResult ajax = AjaxResult.success();
//                ajax.put("url", url);
//                ajax.put("fileName", FileUtils.getName(url));
//                ajax.put("newFileName", FileUtils.getName(url));
//                ajax.put("originalFilename", file.getOriginalFilename());
                if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
                    ajax.put("imgUrl", url);
                    // 更新缓存用户头像
                    loginUser.getUser().setAvatar(url);
                    tokenService.setLoginUser(loginUser);
                    return ajax;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
